package com.atguigu.crud.service;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.management.RuntimeErrorException;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.atguigu.crud.bean.Wxqr;
import com.atguigu.crud.bean.WxqrExample;
import com.atguigu.crud.bean.WxqrExample.Criteria;
import com.atguigu.crud.dao.WxqrMapper;
import com.atguigu.weixin.kit.WeixinKit;
import com.atguigu.weixin.model.WeixinFianlValue;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;


/**
 * 微信二维码扫描
 * @author Administrator
 *
 */
@Service("wxqrService")
public class WxqrService {
	@Autowired
	private	WxqrMapper wxqrMapper;//微信用户业务接口
	
	/**
	 * 添加二维码
	 * @param wxqr
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
 public Wxqr add(Wxqr wxqr) throws IllegalAccessException, InvocationTargetException {
	 wxqr.setId(UUID.randomUUID().toString());
	 if(wxqr.getSnum()==null)throw new RuntimeException("场景值不能为空");
	 //永久二维码
	 if(wxqr.getSnum()<=Wxqr.MAX_BASE_SNUM){
		 Wxqr twq=this.loadBySnum(wxqr.getSnum());
		 if(twq!=null) throw new RuntimeException("固定二维码场景值已经存在");
		 wxqr.setCrdatedate(new Date());
		 setQrTicket(wxqr,0);
		 wxqrMapper.insert(wxqr);
	 }else{//临时二维码
		return addTempQr(wxqr);
	 }
	 return wxqr;
}
 private Wxqr addTempQr(Wxqr wxqr) throws IllegalAccessException, InvocationTargetException {
	 wxqr.setId(UUID.randomUUID().toString());
	 Wxqr twq=this.loadBySnum(wxqr.getSnum());
	 if(twq==null){
		 wxqr.setCrdatedate(new Date());
		 setQrTicket(wxqr, 1);
		 wxqrMapper.insert(wxqr);
		 return wxqr;
		}else{
			//检查是否过期的二维码
			if(checkExpired(twq)){//过期
				 //先删除twq,之后添加wq
				 BeanUtils.copyProperties(wxqr, twq);
				 twq.setCrdatedate(new Date());
				 setQrTicket(twq,1);
				 wxqrMapper.updateByPrimaryKey(twq);
				 return twq;
			}else{//没过期
				wxqr.setSnum((Wxqr.MAX_BASE_SNUM+1)+RandomUtils.nextInt());
				return  addTempQr(wxqr);
			}
		}
	}
 
/**
 * 
 * @param twq
 * @param type 临时
 */
private void setQrTicket(Wxqr twq,int type) {
	String ticket;
	if(type==0){
		ticket=this.loadTicketByBaseQr(twq.getSnum());
	}else{
		ticket=this.loadTicketByTempQr(twq.getSnum());
	}
	 if(ticket==null||"".equals(ticket)) throw new RuntimeException("从微信获取二维码失败！");
	 twq.setTicket(ticket);
	
}
private boolean checkExpired(Wxqr twq) {
	 long t=System.currentTimeMillis()-twq.getCrdatedate().getTime();//当前系统时间 -创建时间
	 //t/1000换成秒
	 if((t/1000)>60)return true;
	return false;
}
public void delete(String id) {
	 wxqrMapper.deleteByPrimaryKey(id);
}
	
 public Wxqr  load(String id) {
	return wxqrMapper.selectByPrimaryKey(id);
}
	
 public void update(Wxqr wxqr) {
	 wxqrMapper.updateByPrimaryKey(wxqr);
}
	
 /**
  * 永久二维码 小于等于100000
  * @param wxqr
  * @return
  */
 public List<Wxqr> listBaseQr() {
	 WxqrExample wxe=new WxqrExample();
	Criteria criteria=wxe.createCriteria();
	 criteria.andSnumLessThanOrEqualTo(Wxqr.MAX_BASE_SNUM);
	 return  wxqrMapper.selectByExample(wxe);
	 
}
	/**
	 * 临时二维码 小于等于100000
	 * @param wxqr
	 * @return
	 */
 public List<Wxqr> listTempQr() {
	 WxqrExample wxe=new WxqrExample();
	 Criteria criteria=wxe.createCriteria();
	 criteria.andSnumGreaterThan(Wxqr.MAX_BASE_SNUM);
	 return  wxqrMapper.selectByExample(wxe);
}
	
 /**
  * 根据场景值
  * @param snum
  * @return
  */
 public Wxqr loadBySnum(int snum) {
	    Wxqr u=new Wxqr();
	    WxqrExample ue=new WxqrExample();
		Criteria criteria=ue.createCriteria();
		criteria.andSnumEqualTo(snum);
		List<Wxqr> ulist=wxqrMapper.selectByExample(ue);
		 if(ulist.size()>0){
			 u=ulist.get(0);
		 }else{
			 u=null;
		 }
		return u;
 }
 
 
 //永久
 public String loadTicketByBaseQr(int snum) {
	 try {
		 String url=WeixinKit.replaceAccToken(WeixinFianlValue.QR_GET);
		 String json = "{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": "+snum+"}}}";
		 String rjson=WeixinKit.sendJsonPost(url, json);
		  if(WeixinKit.checkRequestSuccess(json)){
			  ObjectMapper m=new ObjectMapper();
			  return m.readTree(rjson).get("ticket").asText();  
		   }
	} catch (JsonProcessingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	 return null;
 };
 
 //临时
 public String loadTicketByTempQr(int snum){
	 try {
		 String url=WeixinKit.replaceAccToken(WeixinFianlValue.QR_GET);
		 //180秒
		 String json = "{\"expire_seconds\": 180, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": "+snum+"}}}";
		 String rjson=WeixinKit.sendJsonPost(url, json);
		  if(WeixinKit.checkRequestSuccess(json)){
			  ObjectMapper m=new ObjectMapper();
			  return m.readTree(rjson).get("ticket").asText();  
		   }
	} catch (JsonProcessingException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	 return null;
 }
	
}
